/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TMallPayHandle.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年5月4日 上午11:57:29  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年5月4日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.bean.tmall.PointExchangeBean;
import com.hp.bon.sgw.wh.service.TMallResponseService;
import com.hp.ocs.diameter.message.*;
import org.apache.axis.client.Call;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.xml.stream.XMLInputFactory;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**  
 * @ClassName: TMallPayHandle   
 * @Description:
 * @author: wanghan  
 * @date:2016年   
 */
public class PointExchangeHandler implements IAsynCallHandler{

	private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
	private PrintStream printStream;
	private PointExchangeBean pointExchangeBean;
	private TMallResponseService tmallResponseService;
	private ThreadPoolTaskExecutor asynExecutor;
	private String pubKeyValue;
	private String LeavePoint;
	private String UsedPoint;
	private Call call;
	private String rollbackExchange_url;
	static XMLInputFactory inputFactory = XMLInputFactory.newInstance();
	
	public PointExchangeHandler(PrintStream printStream,PointExchangeBean pointExchangeBean,
			TMallResponseService tmallResponseService,ThreadPoolTaskExecutor asynExecutor,String pubKeyValue,
			String rollbackExchange_url,String LeavePoint,String UsedPoint,Call call)
	{
		this.printStream = printStream;
        this.pointExchangeBean = pointExchangeBean;
        this.tmallResponseService = tmallResponseService;
        this.asynExecutor = asynExecutor;
        this.pubKeyValue = pubKeyValue;
        this.LeavePoint = LeavePoint;
        this.UsedPoint = UsedPoint;
        this.call = call;
        this.rollbackExchange_url = rollbackExchange_url;
	}
	
	@Override
	public int getProtocolType() {
		
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString((Message)response,callParam.getServiceResultCode());
            byte[] resp = respXML.getBytes("UTF-8");
            ack.setLength(resp.length);
            ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库

				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	private String convertResponseString(Message answer, int serviceResultCode) throws Exception
	{
		int result = 0;
		String resultDesc="";
		String response = "";	    	
		Map<String,String> data = new HashMap<String, String>();
		if (serviceResultCode == 0)   //充值成功
		{
			data.put("Result","0");
			data.put("Result_desc","");
			data.put("Acc_Nbr",pointExchangeBean.getAcc_Nbr());
			data.put("Payment_Serial_Nbr",pointExchangeBean.getPayment_Serial_Nbr());
			data.put("UsedPoint",UsedPoint);
			data.put("CurrMonthPoint", LeavePoint);
		}
		else   //充值失败
		{
				//积分返销
			Element root = DocumentHelper.createElement("root");
			Element element = root.addElement("cityId");
		    element.setText(pointExchangeBean.getCityId());
		    element = root.addElement("transactionID");
		    element.setText(pointExchangeBean.getPayment_Serial_Nbr());
            element = root.addElement("orderNbr");//需要返销的兑换凭单号
            element.setText(pointExchangeBean.getPayment_Serial_Nbr());
		    element = root.addElement("channelType");
		    element.setText("46");
            element = root.addElement("requestTime");
            element.setText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            element = root.addElement("costIntegral");
            element.setText(UsedPoint);
		    String s ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"+root.asXML();
		    _log.info("报文:"+s);
		    String reslut =(String)call.invoke(new Object[] { s });// 调用后台webservice服务
			_log.info("返销:" + reslut);
			
			AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
			AVP_Grouped serviceInfomation = new AVP_Grouped(avp);

			AVP resultDescAvp = serviceInfomation.find(92100,Constants.DIAMETER_VENDOR_CT);
			AVP resultAvp = serviceInfomation.find(20631,Constants.DIAMETER_VENDOR_CT);
			 if (resultDescAvp != null){
				 resultDesc = new AVP_UTF8String(resultDescAvp).queryValue();
			}	
			 if (resultAvp != null){
				 result = new AVP_Unsigned32(resultAvp).queryValue();
			}	
			
			data.put("Result",result+"");
			data.put("Result_desc",resultDesc);
			data.put("Acc_Nbr",pointExchangeBean.getAcc_Nbr());
			data.put("Payment_Serial_Nbr",pointExchangeBean.getPayment_Serial_Nbr());
			data.put("UsedPoint",UsedPoint);
			data.put("CurrMonthPoint", "");
		}
		
		response = tmallResponseService.getResponse2(data);
		return response;
	}
	
}
